<script setup>
  import { ref, reactive, onMounted } from 'vue'
  import axios from 'axios'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import lodash from 'lodash'
  import router from '@/router'


    // 创建 API 客户端实例
  const apiClient = axios.create({
    baseURL: 'http://localhost:8087', // 根据实际后端地址修改
    timeout: 10000,
})

  // 添加请求拦截器，如果需要token认证
  apiClient.interceptors.request.use(
      config => {
        // 从localStorage获取token并添加到请求头
        const token = localStorage.getItem('token');
        if (token) {
          config.headers.Authorization = token;
        }
        return config;
      },
      error => {
        return Promise.reject(error);
      }
  );

  // 添加响应拦截器处理通用逻辑
  apiClient.interceptors.response.use(
      response => {
        // 直接返回数据
        return response.data;
      },
      error => {
        // 统一处理错误
        if (error.response && error.response.status === 401) {
          // 未授权，跳转到登录页
          ElMessage.error('认证失败，请重新登录');
          localStorage.removeItem('token');
          router.push('/login');
        } else {
          ElMessage.error('请求失败: ' + (error.response?.data?.msg || error.message));
        }
        return Promise.reject(error);
      }
  );



  const userInfo = ref(null)
  async function getuser(){
    try {
        const response = await apiClient.get(`/user/all`);
      userInfo.value = response.data;
      console.log(userInfo.value);
      return userInfo.value;
    } catch (error) {
      console.error("获取用户信息失败:", error);
      return null;
    }
  }


  const tableData=ref([]);

  const  total=ref(0);
  //定义对话框的显示状态
  const editWinVisible = ref(false);
  //查询数据
  const searchObj=ref({
    current:1,
    size:5,
    total:0,
    realname:'',
    phone:'',
    idcard:'',
  });
  //要修改或者新增的数据
  const obj=ref({});

  const search = async () => {
    try {
      // 使用网关进行分页查询
      const params = {
        current: searchObj.value.current,
        size: searchObj.value.size,
        realname: searchObj.value.realname,
        phone: searchObj.value.phone,
      };
      console.log('请求参数:', params);
      const response = await apiClient.get('/user/page', { params });
      console.log('接口响应:', response); // 查看响应结构
      tableData.value = response.data.records || [];
      total.value = response.data.total || 0;
    } catch (error) {
      console.error("获取用户列表失败:", error);
      ElMessage.error('获取用户列表失败');
      tableData.value = [];
      total.value = 0;
    }

  }
  //页面加载后要挂载的数据
  onMounted(async () => {
    await getuser();
    await search();
  });
  //定义方法

  const handleSizeChange = () => {
    search();
  }
  const handleCurrentChange = () => {
    search();
  }
  const handleSearch = async () => {
    searchObj.value.current=1
    search();
  }
  const handleAdd = () => {
    // 初始化新增对象，包含所有必要字段
    obj.value = {
      nickname: '',
      realname:'',
      phone: '',
      idcard: '',
      email: '',
      status: '0',  // 默认启用状态
      // 其他需要的字段
    };
    editWinVisible.value = true;
  }

  const editCancel = () => {
    obj.value = {};//清空数据
    editWinVisible.value = false;//关闭对话框
  }
  const editCommit = async () => {
    // await api.edit(obj.value);//提交修改数据
    // search();//刷新表格
    // editWinVisible.value = false;//关闭编辑对话框
    try {
      if (obj.value.id) {
        // 编辑操作
        await apiClient.put('/user/edit', obj.value);
        ElMessage.success('编辑成功');
      } else {
        // 新增操作
        await apiClient.post('/user/add', obj.value);
        ElMessage.success('新增成功');
      }
      search(); // 刷新表格
      editWinVisible.value = false; // 关闭编辑对话框
    } catch (error) {
      console.error('操作失败:', error);
      ElMessage.error('操作失败: ' + (error.response?.data?.msg || error.message));
      // 可以添加 Element Plus 的消息提示
      // ElMessage.error('操作失败');
    }
  }

  const handleEdit = (index, row) => {
    obj.value=lodash.clone(row);
    editWinVisible.value = true;
    console.log(index, row)
  }
  const handleDelete = (index, row) => {
    ElMessageBox.confirm(
        '确认删除该行数据吗?',
        '删除提示',
        {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'error',
        }
    )
        .then(async() => {
          try {
            await apiClient.delete(`/user/delete/${row.id}`);
            ElMessage.success('删除成功');
            //重新加载数据
            //设置从第一页开始查询
            searchObj.value.current = 1;
            search();
          } catch (error) {
            ElMessage.error('删除失败: ' + (error.response?.data?.msg || error.message));
          }
        })
        .catch(() => {
          ElMessage.info('已取消删除');
        })
  }

  // 添加状态变更处理方法
  const handleStatusChange = async (user) => {
    try {
      // 调用API更新用户状态
      await apiClient.put('/user/edit', {
        id: user.id,
        status: user.status
      });
      ElMessage.success('状态更新成功');
    } catch (error) {
      console.error('状态更新失败:', error);
      ElMessage.error('状态更新失败: ' + (error.response?.data?.msg || error.message));      // 如果更新失败，回滚状态
      user.status = user.status === 1 ? 0 : 1;
    }
  }


</script>

<template>
  <!--搜索-->
  <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top: 10px">
    <el-form-item label="真实姓名">
      <el-input v-model="searchObj.realname" placeholder="真实姓名" clearable />
    </el-form-item>
    <el-form-item label="手机号">
      <el-input v-model="searchObj.phone" placeholder="手机号" clearable />
    </el-form-item>
  </el-form>
  <el-form :inline="true">
    <el-form-item>
      <el-button type="primary" @click="handleSearch" style="background-color: #c5a7df; border-color: #c5a7df;">查询</el-button>
    </el-form-item>
    <el-form-item >
      <el-button type="primary" @click="handleAdd" style="background-color: #c5a7df; border-color: #c5a7df;">新增</el-button>
    </el-form-item>
  </el-form>

  <el-table
      :data="Array.isArray(tableData) ? tableData : []"
      style="width: 100%"
      height="tableHeight"
      v-loading="tableData.length === 0 && total === 0">
    <el-table-column fixed prop="id" label="序号" width="100" />
    <el-table-column prop="nickname" label="用户昵称" width="160" />
    <el-table-column prop="realname" label="真实姓名" width="160" />
    <el-table-column prop="phone" label="手机号" width="160" />
    <el-table-column prop="idcard" label="身份证号" width="100" />
    <el-table-column prop="email" label="邮箱" width="200" />
    <el-table-column prop="status" label="状态" width="100" >
      <template #default="user">
        <el-switch
            v-model="user.row.status"
            inline-prompt
            class="状态"
            width="60"
            active-text="封禁"
            inactive-text="正常"
            :active-value="1"
            :inactive-value="0"
            active-color="#67c23a"
            inactive-color="#f56c6c"
            @change="handleStatusChange(user.row)"
        >
        </el-switch>
      </template>
    </el-table-column>
<!--    <el-table-column prop="createtime" label="创建时间" width="160" />-->
    <!--    <el-table-column prop="isdel" label="是否删除" width="100" />-->
    <el-table-column label="处理按钮">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)" >
          删除
        </el-button>
      </template>
    </el-table-column>



  </el-table>
  <!--分页-->
  <el-pagination
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.size"
      :page-sizes="[10, 20, 30, 40]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"

  />



  <!--   编辑对话框-->

  <el-dialog v-model="editWinVisible" title="编辑" width="500">
    <el-form :model="obj" label-width="100px">
      <el-form-item label="用户昵称" >
        <el-input v-model="obj.nickname" autocomplete="off" />
      </el-form-item>
      <el-form-item label="真实姓名" >
        <el-input v-model="obj.realname" autocomplete="off" />
      </el-form-item>
      <el-form-item label="手机号 " >
        <el-input v-model="obj.phone" autocomplete="off" />
      </el-form-item>
      <el-form-item label="身份证号" >
        <el-input v-model="obj.idcard" autocomplete="off" />
      </el-form-item>
      <el-form-item label=" 邮箱 " >
        <el-input v-model="obj.email" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="editCommit ">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<style scoped>

</style>